package com.dlc.shop.user.common.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dlc.shop.common.i18n.I18nMessage;
import com.dlc.shop.common.util.PageParam;
import com.dlc.shop.user.common.dao.UserRightsMapper;
import com.dlc.shop.user.common.model.UserRights;
import com.dlc.shop.user.common.model.UserRightsLang;
import com.dlc.shop.user.common.service.UserRightsLangService;
import com.dlc.shop.user.common.service.UserRightsService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 会员等级
 *
 * @author LGH
 * @date 2020-02-26 16:03:14
 */
@Service
@AllArgsConstructor
@Slf4j
public class UserRightsServiceImpl extends ServiceImpl<UserRightsMapper, UserRights> implements UserRightsService {
    private UserRightsMapper userRightsMapper;
    private UserRightsLangService userRightsLangService;

    @Override
    public Boolean setStatua(Long rightsId, Integer status) {
        return userRightsMapper.setStatua(rightsId,status);
    }

    @Override
    public List<Long> getUserRightsIdListByLevelId(Long id ,Integer levelType) {
        return userRightsMapper.getUserRightsIdListByLevelId(id,levelType);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean removeRights(Long rightsId) {
        boolean isSuccess = this.removeById(rightsId);
        userRightsLangService.remove(new LambdaQueryWrapper<UserRightsLang>()
                .eq(UserRightsLang::getRightsId, rightsId));
        return isSuccess;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean  savaUserRights(UserRights userRights) {
        boolean save = this.save(userRights);
        // 保存权益国际化信息
        for (UserRightsLang userRightsLang : userRights.getUserRightsLangList()) {
            userRightsLang.setRightsId(userRights.getRightsId());
        }
        boolean saveBatch = userRightsLangService.saveBatch(userRights.getUserRightsLangList());
        return save && saveBatch;
    }

    @Override
    public UserRights getRightsById(Long rightsId) {
        UserRights rights = this.getById(rightsId);
        // 获取国际化信息
        List<UserRightsLang> userRightsLangList = userRightsLangService.list(new LambdaQueryWrapper<UserRightsLang>()
                .eq(UserRightsLang::getRightsId, rightsId));
        rights.setUserRightsLangList(userRightsLangList);
        return rights;
    }

    @Override
    public IPage<UserRights> getRightsPage(PageParam<UserRights> page, UserRights userRights,Integer lang) {
        IPage<UserRights> userRightsPage = userRightsMapper.pageRights(page, userRights, lang);
        List<UserRights> records = userRightsPage.getRecords();
        this.rightsLang(records);
        return userRightsPage;
    }

    @Override
    public List<UserRights> getRightsList(Long shopId) {
        List<UserRights> rights = this.list(new LambdaQueryWrapper<UserRights>()
                .eq(UserRights::getShopId, shopId)
                .eq(UserRights::getServiceType, 1)
                .orderByAsc(UserRights::getSeq));
        rightsLang(rights);
        return rights;
    }

    /**
     * 权益国际化
     * @param records
     */
    private void rightsLang(List<UserRights> records){
        List<Long> rightsIdList = new ArrayList<>();
        for (UserRights record : records) {
            rightsIdList.add(record.getRightsId());
        }
        if (CollUtil.isEmpty(rightsIdList)){
            return;
        }
        List<UserRightsLang> userRightsLangList = userRightsLangService.list(new LambdaQueryWrapper<UserRightsLang>()
                    .in(UserRightsLang::getRightsId, rightsIdList));
        Map<Long, List<UserRightsLang>> longListMap = userRightsLangList.stream().collect(Collectors.groupingBy(UserRightsLang::getRightsId));
        for (UserRights record : records) {
            List<UserRightsLang> langs = longListMap.get(record.getRightsId());
            if (CollUtil.isEmpty(langs)){
                continue;
            }
            record.setUserRightsLangList(langs);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateRights(UserRights userRights) {
        boolean update = this.updateById(userRights);
        // 国际化信息修改
        boolean saveOrUpdateBatch = userRightsLangService.saveOrUpdateBatch(userRights.getUserRightsLangList());
        return update && saveOrUpdateBatch;
    }

    @Override
    public Map<Long, List<UserRights>> getLevelIdRightsMap(List<Long> levelIds) {
        List<UserRights> userRights = userRightsMapper.listRightByLevelIds(levelIds, I18nMessage.getLang());
        Map<Long, List<UserRights>> levelIdRightsMap = new HashMap<>(16);
        List<UserRights> rights;
        for (UserRights userRight : userRights) {
            rights = levelIdRightsMap.getOrDefault(userRight.getLevelId(), new ArrayList<>());
            rights.add(userRight);
            levelIdRightsMap.put(userRight.getLevelId(), rights);
        }
        return levelIdRightsMap;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void initShopSysRights(Long shopId) {
        // 商家端默认系统权益(包邮，打折，送优惠券)
        List<List<UserRightsLang>> rightLangsList = new ArrayList<>();
        // 包邮
        rightLangsList.add(Arrays.asList(
                new UserRightsLang(0, "包邮", "满足条件后，订单包邮"),
                new UserRightsLang(1, "Free Shipping", "Free shipping after meeting the conditions")
        ));
        // 打折
        rightLangsList.add(Arrays.asList(
                new UserRightsLang(0, "打折", "满足条件后，订单打折"),
                new UserRightsLang(1, "Discount", "Discount after meeting the conditions")
        ));
        // 送优惠券
        rightLangsList.add(Arrays.asList(
                new UserRightsLang(0, "送优惠券", "满足条件后，订单送优惠券"),
                new UserRightsLang(1, "Coupon", "Coupon after meeting the conditions")
        ));
        // 保存商家系统权益
        List<UserRights> rights = this.buildSysRights(shopId, rightLangsList);
        for (UserRights tempRight : rights) {
            this.savaUserRights(tempRight);
        }
    }

    /**
     * 构建系统权益信息
     * @return
     */
    private List<UserRights> buildSysRights(Long shopId, List<List<UserRightsLang>> rightLangsList) {
        List<UserRights> rights = new ArrayList<>();
        for (List<UserRightsLang> rightLangs : rightLangsList) {
            UserRights tempRight = new UserRights(shopId, 0, 1, 0);
            tempRight.setUserRightsLangList(rightLangs);
            rights.add(tempRight);
        }
        return rights;
    }
}
